"use client"

import { useState, useMemo } from "react"
import { useParams, useNavigate, Link } from "react-router-dom"
import {
  Button,
  Typography,
  Breadcrumb,
  Spin,
  Empty,
  Modal,
  Input,
  Card,
  Tag,
  Table,
  Tooltip,
  Divider,
  Select,
  Row,
  Col,
  Form,
  Space,
  Tabs,
} from "antd"
import {
  TeamOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  ArrowLeftOutlined,
  CopyOutlined,
  SearchOutlined,
  FilterOutlined,
  GlobalOutlined,
  ApiOutlined,
  CodeOutlined,
  BugOutlined,
  RocketOutlined,
  AppstoreOutlined,
  DatabaseOutlined,
} from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"
import HostsBlockForm from "../components/HostsBlockForm"
import type { HostsBlock, Module, HostTypeDefinition } from "../types"
import "../styles/global.scss"
import "./ProjectDetail.scss"

const { Title, Text } = Typography
const { confirm } = Modal
const { Option } = Select
const { TabPane } = Tabs

const ProjectDetail = () => {
  const { projectId } = useParams<{ projectId: string }>()
  const navigate = useNavigate()
  const {
    projects,
    departments,
    modules,
    hostsBlocks,
    hostTypes,
    loading,
    addHostsBlock,
    updateHostsBlock,
    deleteHostsBlock,
    addModule,
    updateModule,
    deleteModule,
  } = useHosts()

  const [isHostsBlockModalVisible, setIsHostsBlockModalVisible] = useState(false)
  const [isModuleModalVisible, setIsModuleModalVisible] = useState(false)
  const [editingHostsBlock, setEditingHostsBlock] = useState<HostsBlock | null>(null)
  const [editingModule, setEditingModule] = useState<Module | null>(null)
  const [searchText, setSearchText] = useState("")
  const [selectedType, setSelectedType] = useState<string | undefined>(undefined)
  const [viewMode, setViewMode] = useState<"card" | "table">("card")
  const [moduleForm] = Form.useForm()
  const [activeTab, setActiveTab] = useState("all")

  if (!projectId) {
    navigate("/projects")
    return null
  }

  const project = projects.find((p) => p.id === projectId)
  const department = project ? departments.find((d) => d.id === project.departmentId) : undefined
  const projectModules = modules.filter((m) => m.projectId === projectId)

  // Filter hosts by search, type, and active tab
  const filteredHostsBlocks = useMemo(() => {
    const filtered = hostsBlocks
      .filter((h) => h.projectId === projectId)
      .filter((h) => {
        const matchesSearch =
          !searchText ||
          h.name.toLowerCase().includes(searchText.toLowerCase()) ||
          h.content.toLowerCase().includes(searchText.toLowerCase()) ||
          (h.description && h.description.toLowerCase().includes(searchText.toLowerCase()))

        const matchesType = !selectedType || h.environment === selectedType

        const matchesTab = activeTab === "all" || h.environment === activeTab

        return matchesSearch && matchesType && matchesTab
      })
    return filtered
  }, [hostsBlocks, projectId, searchText, selectedType, activeTab])

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
      </div>
    )
  }

  if (!project) {
    return (
      <div className="empty-container">
        <Empty description="项目不存在或已被删除">
          <Button type="primary" onClick={() => navigate("/projects")}>
            返回项目列表
          </Button>
        </Empty>
      </div>
    )
  }

  const handleAddHostsBlock = () => {
    setEditingHostsBlock(null)
    setIsHostsBlockModalVisible(true)
  }

  const handleEditHostsBlock = (hostsBlock: HostsBlock) => {
    setEditingHostsBlock(hostsBlock)
    setIsHostsBlockModalVisible(true)
  }

  const handleHostsBlockSubmit = (values: any) => {
    if (editingHostsBlock) {
      updateHostsBlock(editingHostsBlock.id, {
        name: values.name,
        content: values.content,
        description: values.description,
        environment: values.environment,
      })
    } else {
      addHostsBlock({
        name: values.name,
        projectId,
        content: values.content,
        description: values.description,
        environment: values.environment,
      })
    }
    setIsHostsBlockModalVisible(false)
    setEditingHostsBlock(null)
  }

  const handleDeleteHostsBlock = (id: string, name: string) => {
    confirm({
      title: "确定要删除此 Hosts 配置吗?",
      icon: <ExclamationCircleOutlined />,
      content: `删除配置 "${name}" 后将无法恢复。`,
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        deleteHostsBlock(id)
      },
    })
  }

  const handleAddModule = () => {
    setEditingModule(null)
    moduleForm.resetFields()
    setIsModuleModalVisible(true)
  }

  const handleEditModule = (module: Module) => {
    setEditingModule(module)
    moduleForm.setFieldsValue({
      name: module.name,
      description: module.description,
    })
    setIsModuleModalVisible(true)
  }

  const handleModuleSubmit = async () => {
    try {
      const values = await moduleForm.validateFields()

      if (editingModule) {
        updateModule(editingModule.id, {
          name: values.name,
          description: values.description,
        })
      } else {
        addModule({
          name: values.name,
          projectId,
          description: values.description,
        })
      }

      setIsModuleModalVisible(false)
      setEditingModule(null)
    } catch (error) {
      console.error("Form validation failed:", error)
    }
  }

  const handleDeleteModule = (id: string, name: string) => {
    confirm({
      title: "确定要删除此模块吗?",
      icon: <ExclamationCircleOutlined />,
      content: `删除模块 "${name}" 后将无法恢复。`,
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        deleteModule(id)
      },
    })
  }

  const handleCopyContent = (content: string) => {
    navigator.clipboard.writeText(content)
    Modal.success({
      title: "复制成功",
      content: "Hosts 配置内容已复制到剪贴板",
    })
  }

  const handleReset = () => {
    setSearchText("")
    setSelectedType(undefined)
  }

  // Get the department color
  const getDepartmentColor = () => {
    return department?.color || "#3b82f6"
  }

  // Get host type info
  const getHostTypeInfo = (type: string): HostTypeDefinition | undefined => {
    const foundType = hostTypes.find((t) => t.name === type)
    if (foundType) return foundType

    // Fallback mapping for environment types that might not be in hostTypes
    const environmentMapping: Record<string, { color: string; icon: string }> = {
      前端: { color: "#3b82f6", icon: "GlobalOutlined" },
      后端: { color: "#8b5cf6", icon: "ApiOutlined" },
      开发: { color: "#10b981", icon: "CodeOutlined" },
      测试: { color: "#f59e0b", icon: "BugOutlined" },
      预发布: { color: "#f97316", icon: "RocketOutlined" },
      生产: { color: "#ef4444", icon: "RocketOutlined" },
    }

    if (environmentMapping[type]) {
      return {
        id: type,
        code: "other",
        name: type,
        color: environmentMapping[type].color,
        icon: environmentMapping[type].icon,
        createdAt: new Date().toISOString(),
      }
    }

    return undefined
  }

  // Get icon component based on icon name
  const getIconComponent = (iconName: string) => {
    switch (iconName) {
      case "GlobalOutlined":
        return <GlobalOutlined />
      case "ApiOutlined":
        return <ApiOutlined />
      case "DatabaseOutlined":
        return <DatabaseOutlined />
      case "CodeOutlined":
        return <CodeOutlined />
      case "BugOutlined":
        return <BugOutlined />
      case "RocketOutlined":
        return <RocketOutlined />
      default:
        return <AppstoreOutlined />
    }
  }

  const columns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      width: "20%",
      render: (text: string, record: HostsBlock) => {
        const typeInfo = getHostTypeInfo(record.environment)
        return (
          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
            {typeInfo && (
              <div
                style={{
                  width: "24px",
                  height: "24px",
                  borderRadius: "4px",
                  backgroundColor: typeInfo.color,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: "white",
                }}
              >
                {getIconComponent(typeInfo.icon)}
              </div>
            )}
            <span className="hosts-name">{text}</span>
          </div>
        )
      },
    },
    {
      title: "类型",
      dataIndex: "environment",
      key: "environment",
      width: "10%",
      render: (text: string) => {
        const typeInfo = getHostTypeInfo(text)
        return (
          <Tag
            style={{
              background: typeInfo ? `${typeInfo.color}20` : "#f3f4f6",
              color: typeInfo ? typeInfo.color : "#4b5563",
              borderRadius: "12px",
              border: "none",
            }}
          >
            {typeInfo && getIconComponent(typeInfo.icon)}
            <span style={{ marginLeft: typeInfo ? "4px" : "0" }}>{text}</span>
          </Tag>
        )
      },
    },
    {
      title: "内容预览",
      dataIndex: "content",
      key: "content",
      width: "40%",
      render: (text: string) => (
        <div className="content-preview">
          {text
            .split("\n")
            .slice(0, 2)
            .map((line, index) => (
              <div key={index} className={line.trim().startsWith("#") ? "comment-line" : ""}>
                {line}
              </div>
            ))}
          {text.split("\n").length > 2 && <div className="more-indicator">...</div>}
        </div>
      ),
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
      width: "15%",
      render: (text: string) => <span className="hosts-description">{text || "-"}</span>,
    },
    {
      title: "操作",
      key: "action",
      width: "15%",
      render: (_: any, record: HostsBlock) => (
        <div className="table-actions">
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              size="small"
              onClick={() => handleEditHostsBlock(record)}
              className="action-button"
            />
          </Tooltip>
          <Tooltip title="复制内容">
            <Button
              type="text"
              icon={<CopyOutlined />}
              size="small"
              onClick={() => handleCopyContent(record.content)}
              className="action-button"
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => handleDeleteHostsBlock(record.id, record.name)}
              className="action-button-danger"
            />
          </Tooltip>
        </div>
      ),
    },
  ]

  // Module columns for table view
  const moduleColumns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      render: (text: string) => <span style={{ fontWeight: 500 }}>{text}</span>,
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
      ellipsis: true,
      render: (text: string) => text || "-",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: "操作",
      key: "action",
      width: 180,
      render: (_: any, record: Module) => (
        <Space>
          <Button type="primary" size="small" onClick={() => navigate(`/projects/${projectId}/modules/${record.id}`)}>
            查看
          </Button>
          <Button type="text" icon={<EditOutlined />} size="small" onClick={() => handleEditModule(record)} />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            size="small"
            onClick={() => handleDeleteModule(record.id, record.name)}
          />
        </Space>
      ),
    },
  ]

  // Get unique environment types for tabs
  const environmentTypes = hostTypes.map((type) => type.name)

  return (
    <div className="container">
      <Breadcrumb className="breadcrumb mb-4">
        <Breadcrumb.Item>
          <Link to="/">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to="/projects">项目管理</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>{project.name}</Breadcrumb.Item>
      </Breadcrumb>

      <div className="project-header-card mb-6">
        <div className="project-header">
          <div className="project-info">
            <div className="project-title-container">
              <div
                className="project-icon circle-icon-enhanced"
                style={{
                  background: `linear-gradient(135deg, ${getDepartmentColor()} 0%, ${getDepartmentColor()}80 100%)`,
                }}
              >
                {project.name.charAt(0).toUpperCase()}
              </div>
              <div>
                <Title level={4} className="project-title m-0">
                  {project.name}
                </Title>
                <div className="tag-container" style={{ marginTop: "4px" }}>
                  {department && (
                    <Tag
                      className="tag-green"
                      style={{
                        background: `${getDepartmentColor()}20`,
                        color: getDepartmentColor(),
                        borderRadius: "12px",
                        border: "none",
                      }}
                    >
                      <TeamOutlined className="tag-icon" /> {department.name}
                    </Tag>
                  )}
                </div>
              </div>
            </div>

            {project.description && (
              <Text type="secondary" className="project-description">
                {project.description}
              </Text>
            )}
          </div>
          <div className="project-actions">
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate("/projects")}>
              返回
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddHostsBlock}>
              添加 Hosts 配置
            </Button>
          </div>
        </div>

        <Divider className="divider" />

        <div className="project-stats">
          <div className="stat-item">
            <div className="stat-value">{projectModules.length}</div>
            <div className="stat-label">模块总数</div>
          </div>
          <div className="stat-item" style={{ marginLeft: "32px" }}>
            <div className="stat-value">{hostsBlocks.filter((h) => h.projectId === projectId).length}</div>
            <div className="stat-label">配置总数</div>
          </div>
        </div>
      </div>

      <Card className="hosts-card mb-6">
        <div className="hosts-card-header">
          <Title level={5} className="hosts-card-title m-0">
            Hosts 配置列表
          </Title>
          <div className="view-mode-selector">
            <Button
              className={`view-mode-button ${viewMode === "card" ? "active" : ""}`}
              size="small"
              onClick={() => setViewMode("card")}
            >
              卡片视图
            </Button>
            <Button
              className={`view-mode-button ${viewMode === "table" ? "active" : ""}`}
              size="small"
              onClick={() => setViewMode("table")}
            >
              表格视图
            </Button>
          </div>
        </div>

        <Divider className="divider" />

        <div className="filter-container">
          <div className="filter-controls">
            <Input
              placeholder="搜索配置..."
              prefix={<SearchOutlined className="search-icon" />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
              className="filter-input"
            />

            <Select
              placeholder="选择类型"
              allowClear
              value={selectedType}
              onChange={(value) => setSelectedType(value)}
              className="filter-select"
            >
              {environmentTypes.map((type) => (
                <Option key={type} value={type}>
                  {type}
                </Option>
              ))}
            </Select>

            <Button icon={<FilterOutlined />} onClick={handleReset}>
              重置
            </Button>

            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddHostsBlock}>
              添加配置
            </Button>
          </div>
        </div>

        <Tabs activeKey={activeTab} onChange={setActiveTab} className="mb-4">
          <TabPane tab="全部" key="all" />
          {environmentTypes.map((type) => {
            const typeInfo = getHostTypeInfo(type)
            return (
              <TabPane
                tab={
                  <span>
                    {typeInfo && getIconComponent(typeInfo.icon)}
                    <span style={{ marginLeft: "4px" }}>{type}</span>
                  </span>
                }
                key={type}
              />
            )
          })}
        </Tabs>

        <div className="hosts-content">
          {filteredHostsBlocks.length === 0 ? (
            <Empty description="暂无配置">
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAddHostsBlock}>
                添加配置
              </Button>
            </Empty>
          ) : viewMode === "table" ? (
            <Table
              columns={columns}
              dataSource={filteredHostsBlocks}
              rowKey="id"
              pagination={false}
              size="small"
              className="hosts-table"
            />
          ) : (
            <Row gutter={[16, 16]}>
              {filteredHostsBlocks.map((block) => {
                const typeInfo = getHostTypeInfo(block.environment)
                const typeColor = typeInfo?.color || "#6b7280"
                const typeIcon = typeInfo ? getIconComponent(typeInfo.icon) : <AppstoreOutlined />

                return (
                  <Col xs={24} sm={12} md={8} key={block.id}>
                    <Card
                      className="hosts-block-card"
                      hoverable
                      style={{
                        boxShadow: "0 1px 2px rgba(0, 0, 0, 0.03)",
                        transition: "all 0.3s ease",
                        border: "1px solid #f1f5f9",
                      }}
                    >
                      <div className="hosts-block-header">
                        <div
                          className="hosts-block-icon circle-icon-enhanced"
                          style={{
                            background: `linear-gradient(135deg, ${typeColor} 0%, ${typeColor}80 100%)`,
                            color: "white",
                          }}
                        >
                          {typeIcon}
                        </div>
                        <div className="hosts-block-info">
                          <div className="hosts-block-title">{block.name}</div>
                          <Tag
                            style={{
                              background: `${typeColor}20`,
                              color: typeColor,
                              border: "none",
                              borderRadius: "12px",
                              padding: "0 8px",
                            }}
                          >
                            {typeIcon}
                            <span style={{ marginLeft: "4px" }}>{block.environment}</span>
                          </Tag>
                        </div>
                      </div>

                      {block.description && <div className="hosts-block-description">{block.description}</div>}

                      <div className="hosts-block-content" style={{ background: `${typeColor}10` }}>
                        {block.content
                          .split("\n")
                          .slice(0, 4)
                          .map((line, index) => (
                            <div key={index} className={line.trim().startsWith("#") ? "comment-line" : ""}>
                              {line}
                            </div>
                          ))}
                        {block.content.split("\n").length > 4 && <div className="more-indicator">...</div>}
                      </div>

                      <div className="hosts-block-footer">
                        <Text className="hosts-block-date">{new Date(block.updatedAt).toLocaleDateString()}</Text>
                        <div className="hosts-block-actions">
                          <Button
                            type="text"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={() => handleEditHostsBlock(block)}
                            className="action-button"
                          />
                          <Button
                            type="text"
                            size="small"
                            icon={<CopyOutlined />}
                            onClick={() => handleCopyContent(block.content)}
                            className="action-button"
                          />
                          <Button
                            type="text"
                            danger
                            size="small"
                            icon={<DeleteOutlined />}
                            onClick={() => handleDeleteHostsBlock(block.id, block.name)}
                            className="action-button-danger"
                          />
                        </div>
                      </div>
                    </Card>
                  </Col>
                )
              })}
            </Row>
          )}
        </div>
      </Card>

      {/* Add/Edit Hosts Block Modal */}
      <Modal
        title={editingHostsBlock ? "编辑 Hosts 配置" : "添加 Hosts 配置"}
        open={isHostsBlockModalVisible}
        onCancel={() => {
          setIsHostsBlockModalVisible(false)
          setEditingHostsBlock(null)
        }}
        footer={null}
        width={680}
      >
        <HostsBlockForm
          initialValues={
            editingHostsBlock
              ? {
                  name: editingHostsBlock.name,
                  content: editingHostsBlock.content,
                  description: editingHostsBlock.description,
                  environment: editingHostsBlock.environment,
                }
              : undefined
          }
          onSubmit={handleHostsBlockSubmit}
          onCancel={() => {
            setIsHostsBlockModalVisible(false)
            setEditingHostsBlock(null)
          }}
          environmentTypes={environmentTypes}
        />
      </Modal>

      {/* Add/Edit Module Modal */}
      <Modal
        title={editingModule ? "编辑模块" : "添加模块"}
        open={isModuleModalVisible}
        onOk={handleModuleSubmit}
        onCancel={() => {
          setIsModuleModalVisible(false)
          setEditingModule(null)
        }}
        okText={editingModule ? "更新" : "添加"}
        cancelText="取消"
      >
        <Form form={moduleForm} layout="vertical" style={{ marginTop: "16px" }}>
          <Form.Item name="name" label="模块名称" rules={[{ required: true, message: "请输入模块名称" }]}>
            <Input placeholder="请输入模块名称" />
          </Form.Item>
          <Form.Item name="description" label="模块描述">
            <Input.TextArea rows={4} placeholder="请输入模块描述" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default ProjectDetail
